﻿using K9Nano.Updater.Exceptions;

namespace K9Nano.Updater.Utils;

internal static class PathUtils
{
    public static void ForceDeleteDirectory(string targetDir, int maxRetries = 3, int delayMs = 100)
    {
        if (!Directory.Exists(targetDir)) return;

        // 遍历并强制删除子目录和文件
        foreach (string subDir in Directory.GetDirectories(targetDir))
        {
            ForceDeleteDirectory(subDir, maxRetries, delayMs);
        }

        // 删除所有文件，并处理重试
        foreach (string file in Directory.GetFiles(targetDir))
        {
            ForceDeleteFile(file, maxRetries, delayMs);
        }

        // 删除目录本身，处理可能的锁定或权限问题
        RetryOperation(() =>
        {
            Directory.Delete(targetDir, false);
        }, maxRetries, delayMs);
    }

    public static void ForceDeleteFile(string filePath, int maxRetries, int delayMs)
    {
        RetryOperation(() =>
        {
            // 移除可能的只读属性
            if (File.Exists(filePath))
            {
                File.SetAttributes(filePath, FileAttributes.Normal);
                File.Delete(filePath);
            }
        }, maxRetries, delayMs);
    }

    private static void RetryOperation(Action action, int maxRetries, int delayMs)
    {
        for (int i = 0; i < maxRetries; i++)
        {
            try
            {
                action();
                return; // 操作成功，退出循环
            }
            catch (IOException) when (i < maxRetries - 1)
            {
                Thread.Sleep(delayMs); // 等待后重试
            }
            catch (UnauthorizedAccessException) when (i < maxRetries - 1)
            {
                Thread.Sleep(delayMs);
            }
        }
    }

    public static void MoveToSubDirectory(string parentDirectory, string subFile, string destinationSubDirectory, bool overwrite = true)
    {
        var relativePath = parentDirectory.EndsWith(Path.DirectorySeparatorChar)
            ? parentDirectory
            : (parentDirectory + Path.DirectorySeparatorChar);

        if (!subFile.StartsWith(relativePath, StringComparison.OrdinalIgnoreCase))
        {
            throw new UpdateException($"{subFile}不是{parentDirectory}的下级路径");
        }

        var relativeFile = subFile.Substring(relativePath.Length);

        var targetFile = Path.Combine(destinationSubDirectory, relativeFile);

        new FileInfo(targetFile).Directory?.Create();

        File.Move(subFile, targetFile, overwrite);
    }

    public static void MoveDirectory(string source, string  destination, bool overwrite = true)
    {
        foreach (var item in Directory.EnumerateFiles(source, "*", SearchOption.AllDirectories))
        {
            MoveToSubDirectory(source, item, destination, overwrite);
        }
    }

    public static string CombineFileUri(string path, string fileUri)
    {
        string fullPath;
        if (fileUri.Contains(Path.AltDirectorySeparatorChar))
        {
            fullPath = Path.Combine(path, fileUri.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar));
        }
        else
        {
            fullPath = Path.Combine(path, fileUri);
        }
        var dir = Path.GetDirectoryName(fullPath);
        if(dir != null)  Directory.CreateDirectory(dir);
        return fullPath;
    }
}